package android.vstore.fragment;

import gin.dev.update.DownloadQuere;
import gin.dev.update.DownloadTask;
import gin.dev.update.IOnDownload;
import gin.dev.update.Installation;

import java.io.File;
import java.util.ArrayList;

import com.appvn2014.appstorevn.R;
import com.nostra13.universalimageloader.core.imageaware.ImageAware;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;

import DTO.ImageDTO;
import DTO.ProductDTO;
import DTO.TopicDTO;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.PopupMenu.OnDismissListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.vstore.activities.MainActivity;
import android.vstore.activities.SceneDetailItemActivity;
import android.vstore.fragment.PageHorizalGalleryFragment.ProductListAdapter.ViewHolderProduct;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import anroid.vstore.provider.Constant;
import anroid.vstore.provider.Helper;
import anroid.vstore.provider.Navigator;
import anroid.vstore.provider.UpdateSttListThread;

public class PageSectionFragment extends BaseFragment implements  OnScrollListener, OnItemClickListener {

	FragmentActivity _activity;
	private View rootView;
	private ListView lv_lstProds;
	public ArrayList<ProductDTO> _lstItem = new ArrayList<ProductDTO>();;
	public boolean isProductsLoading = false;
	public boolean isNomoreLoading = false;

	private ProgressBar pb;
	CustomAdapterVerticalProduct adapter;
	public boolean isReload;

	private int catergory;
	private int type;
	public int topic;
	public int event;
	private Loader loader;
	Handler _parentHandler;
	int pagesize = 15;
	private UpdateSttListThread sttlloader;
	
	
	public static PageSectionFragment newInstance(FragmentActivity activity,int id,int cat,int typ,int top,int event,Handler parent)
	{
		PageSectionFragment page = new PageSectionFragment();
		page._activity = activity;
		page.isReload = true;
		page.name = TopicDTO.getName(top);
		page.id = id;
		page.catergory = cat;
		page.type = typ;
		page.topic = top;
		page.event = event;
		page._parentHandler = parent;
		return page;

	}
	int ready = 0;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_sectionpage, container, false);
		InitGUI();
		ready++;
		if(ready == 2)
			Load();
		return rootView;
	}
	@Override
	public void onStart()
	{
		super.onStart();
	}
	@Override
	public void setMenuVisibility(final boolean visible) {
		super.setMenuVisibility(visible);
		if (!visible) {
			//not visible anymore
		}else{
			ready++;
			if (ready == 2 &&visible && _lstItem.size() == 0) {
				Load();
			}
			else {  }

		}
	}

	//	@Override
	//	public void setUserVisibleHint(boolean isVisibleToUser) {
	//	    super.setUserVisibleHint(isVisibleToUser);
	////	    if(!isReadyView)
	////	    	Oncre
	//	    ready++;
	//	    if (ready == 2 &&isVisibleToUser && _lstItem.size() == 0) {
	//	    	Load();
	//	    }
	//	    else {  }
	//	}

	// ==================================================================================
	// Reload list apk to check item row state
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		// reload
		Message sms = new Message();
		sms.what =  Constant.REFRESH_ALL_PAGE;
		_messageHandler.handleMessage(sms);
	}

	// ==================================================================================

	@Override
	public void onPause()
	{
		if(loader != null)
			loader.cancel(true);
		super.onPause();
	}
	public void InitGUI()
	{

		lv_lstProds = (ListView)rootView.findViewById(R.id.lv_prods);
		pb = (ProgressBar) rootView.findViewById(R.id.pb_listview_loading);
		pb.setVisibility(View.INVISIBLE);
		lv_lstProds.setOnItemClickListener(this);
		lv_lstProds.setOnScrollListener(this);
		lv_lstProds.setItemsCanFocus(false);
		lv_lstProds.setDividerHeight(0);
		adapter = new CustomAdapterVerticalProduct(_activity	, R.layout.item_list_prods	, _lstItem);
		lv_lstProds.setAdapter(adapter);

	}
	public void Load()
	{
		if(isNomoreLoading )
			return;
		if(isReload )
		{
			_lstItem.clear();
		}
		loader = new Loader();
		(loader).execute();
		isReload = false;

	}
	public void Reload()
	{
		_lstItem = new ArrayList<ProductDTO>();
		adapter = new CustomAdapterVerticalProduct(_activity	, R.layout.item_list_prods	, _lstItem);
		lv_lstProds.setAdapter(adapter);
		isReload = true;
		isNomoreLoading = false;
		Load();
	}
	public class Loader extends AsyncTask<String, Void, ArrayList<ProductDTO>>{
		

		@Override
		protected ArrayList<ProductDTO> doInBackground(String... params) {

			//			int pagesize = 10;
			ArrayList<ProductDTO> lstProds = DAO.ProductDAO.GetProds(_activity, getCatergory(), getType(), topic, 0, _lstItem.size()+pagesize);
			if(lstProds.size() < _lstItem.size()+pagesize)
				isNomoreLoading = true;
			return lstProds;
		}      

		@Override
		protected void onPostExecute(ArrayList<ProductDTO> lstVipProd) {

			//			HideLoaderPending();
			isProductsLoading  = false;
			if(this == null && ! PageSectionFragment.this.isDetached())
				return;


			if(_lstItem != null && lstVipProd.size() > _lstItem.size())
			{
				int startindx = _lstItem.size();
				_lstItem.addAll(lstVipProd.subList(startindx, lstVipProd.size()));
				adapter.notifyDataSetChanged();
				//				adapter.notifyDataSetInvalidated();
			}
			if(sttlloader == null)
			{
				sttlloader = new UpdateSttListThread(_activity, _messageHandler, _lstItem, 0, _lstItem.size());
				sttlloader.Load();
			}else
				sttlloader.LoadMore(_lstItem.size());
		}

		@Override
		protected void onPreExecute() {
			if(isProductsLoading )
			{
				this.cancel(true);
				//				HideLoaderPending();
				return;
			}
			isProductsLoading = true;
			//			ShowLoaderPending();	
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	protected void ShowLoaderPending()
	{		
		pb.setVisibility(View.VISIBLE);
	}
	protected void HideLoaderPending()
	{
		pb.setVisibility(View.INVISIBLE);
	}
	public Handler _messageHandler = new Handler(){
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == Constant.REFRESH_ALL_PAGE)
			{
				if(adapter != null)
					adapter.notifyDataSetChanged();  
			}else
				if(msg.what == Constant.RECHECK_ALL_PAGE)
				{
					if(sttlloader == null)
					{
						sttlloader = new UpdateSttListThread(_activity, _messageHandler, _lstItem, 0, _lstItem.size());
						sttlloader.Load();
					}else
					{
						sttlloader._start = 0;
						sttlloader._end = _lstItem.size()-1;
						sttlloader.LoadMore(_lstItem.size());
					}
				}
		}
	};

	public class CustomAdapterVerticalProduct extends ArrayAdapter<ProductDTO>
	{
		ArrayList<ProductDTO> itemList;
		//		Boolean isInvalidated = true;
		//		String stt = getResources().getString(R.string.detail_activity_view_app);
		public Activity context;
		public LayoutInflater inflater;
		private final String TAG = "CustomAdapterProduct";

		public CustomAdapterVerticalProduct(Activity context, int textViewResource, ArrayList<ProductDTO> itemList) 
		{
			super(context, textViewResource, itemList);

			this.context = context;
			this.itemList = itemList; 

			this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		} 

		@Override 
		public int getCount() 
		{
			return itemList.size();
		}

		@Override
		public ProductDTO getItem(int position) 
		{
			return itemList.get(position);
		}

		@Override
		public long getItemId(int position) 
		{
			return 0;
		}

		public class ViewHolderProduct
		{
			public ImageView imgViewLogo;
			public ImageAware imgAwareLogo;
			public TextView txtViewTitle;
			public TextView txtViewTime;
			public TextView btnViewAppStatus;
			public ImageView ivViewMenu;
			public ImageView ivViewStatus;

			public TextView txtViewOwner;
			public TextView txtViewCat;
			public TextView txtViewSize;
			public Object lastImageUrl;
		}

		private String CheckDownloading(ViewHolderProduct holder, ProductDTO item )
		{
			String stt;
			//			ProductDTO item = itemList.get(pos);
			int downloadID = DownloadQuere.CheckDownloading(item.packageName);
			if(downloadID != -1)
			{
				DownloadTask task = DownloadQuere.mTaskQuere.get(downloadID);
				if(task.IsFinished() == false)
				{
					// if downloading is still in process
					holder.btnViewAppStatus.setVisibility(View.VISIBLE);
					stt = context.getString(R.string.detail_activity_downloading_app);
					//					holder.btnViewLocation.setText(context.getString(R.string.detail_activity_downloading_app));

				}
				else
				{
					// if downloading is finished 
					DownloadQuere.ClearTask(task);
					stt = context.getString(R.string.detail_activity_downloading_app);
					holder.btnViewAppStatus.setVisibility(View.VISIBLE);
				}
			}
			else	
			{
				// if package is already downloaded
				if(Installation.AlreadyDownloaded(context, item.packageName) == true)
				{
					//					holder.btnViewLocation.setText(R.string.detail_activity_install_app);
					stt = context.getString(R.string.detail_activity_downloaded_app);
					holder.btnViewAppStatus.setVisibility(View.VISIBLE);
				}

				// check if item was installed
				else if(Installation.IsInstalled(context, item.packageName) == true)
				{
					//					holder.btnViewLocation.setText(R.string.detail_activity_open_app_name);
					stt = context.getString(R.string.detail_activity_open_app_name);
					holder.btnViewAppStatus.setVisibility(View.VISIBLE);

					// remove apk after installing
					Installation.DeleteApk(context, item.packageName);

					// post installled success event to server
					String deviceID = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
					Installation.PostInfoInstallSuccess(deviceID, item.id + "");
				}else // not yet down
				{
					//					holder.btnViewLocation.setText(R.string.detail_activity_view_app);
					stt = context.getString(R.string.detail_activity_view_app);
					holder.btnViewAppStatus.setVisibility(View.VISIBLE);
				}


			}
			//	    	holder.btnViewLocation.setText(stt);?
			return stt;
			//	    	_parentHandler.sendMessage(Message.obtain(_messageHandler, REFRESH_ALL_PAGE, 0, 0, null));
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) 
		{	    	
			final ViewHolderProduct holder;
			final int pos = position;
			if(convertView == null) 
			{
				holder = new ViewHolderProduct();
				convertView = inflater.inflate(R.layout.item_list_prods, null);

				holder.imgViewLogo = (ImageView) convertView.findViewById(R.id.iv_itemlistproduct_logo);
				holder.imgAwareLogo = new ImageViewAware(holder.imgViewLogo, false);
				holder.txtViewTitle = (TextView) convertView.findViewById(R.id.tv_itemlistproduct_title);
				holder.txtViewOwner = (TextView)  convertView.findViewById(R.id.tv_itemlistproduct_publisher);
				holder.txtViewSize = (TextView)convertView.findViewById(R.id.tv_itemlistproduct_size);
				holder.txtViewCat = (TextView)convertView.findViewById(R.id.tv_itemlistproduct_cat);
				holder.btnViewAppStatus = (TextView) convertView.findViewById(R.id.btn_itemlistproduct_status);
				holder.ivViewMenu = (ImageView) convertView.findViewById(R.id.iv_itemlistproduct_menu);
				holder.ivViewStatus = (ImageView) convertView.findViewById(R.id.iv_itemlistproduct_status);
				convertView.setTag(holder);
			}
			else
				holder = (ViewHolderProduct)convertView.getTag();
			//			ProductDTO.VerifyAppStatus(activity, itemList.get(position));
			ProductDTO bean = (ProductDTO) itemList.get(position);

			if(bean == null) return convertView;

			if (holder.lastImageUrl == null || !holder.lastImageUrl.equals(bean.imgURL)
					|| holder.imgViewLogo.getDrawable() == null) {
				// refresh image
				holder.lastImageUrl = bean.imgURL;
				ImageDTO.displayImage( bean.imgURL, holder.imgAwareLogo); 
			} else {
				// do nothing, image did not change and does not need to be updated
			}

			if(itemList.get(position).isInvalidated)
			{
				//				ProductDTO.VerifyAppStatus(activity, itemList.get(position));
				itemList.get(position).isInvalidated = false;
			}
			switch (itemList.get(position).status) {
			case Constant.APP_STT_INSTALLED:
				holder.ivViewStatus.setVisibility(View.VISIBLE);
				holder.btnViewAppStatus.setVisibility(View.INVISIBLE);
				holder.ivViewStatus.setImageResource(R.drawable.ic_check);
				break;
			case Constant.APP_STT_UPDATE:
				holder.ivViewStatus.setVisibility(View.VISIBLE);
				holder.btnViewAppStatus.setText(itemList.get(position).sttStr);
				holder.btnViewAppStatus.setVisibility(View.VISIBLE);
				holder.ivViewStatus.setImageResource(R.drawable.ic_update);
				break;
			default:
				holder.btnViewAppStatus.setVisibility(View.INVISIBLE);
				holder.ivViewStatus.setVisibility(View.INVISIBLE);

				break;
			}

			holder.txtViewTitle.setText(bean.name);
			holder.txtViewOwner.setText(bean.publisher);
			holder.txtViewSize.setText(" | " + bean.size);
			holder.txtViewCat.setText(bean.category.trim());

			holder.ivViewMenu.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(final View v) {
					// TODO Auto-generated method stub
					((ImageView)v).setImageResource(R.drawable.ic_menu);
					PopupMenu popup = new PopupMenu(_activity, v);
					popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());
					if(itemList.get(position).status == Constant.APP_STT_NOTHING )
					{
						popup.getMenu().getItem(0).setTitle(_activity.getString(R.string.detail_activity_view_app));
						popup.getMenu().getItem(1).setTitle(_activity.getString(R.string.detail_activity_view_detail_app));
					
					}else if(itemList.get(position).status == Constant.APP_STT_DOWNLOADED )
					{
						popup.getMenu().getItem(0).setTitle(_activity.getString(R.string.detail_activity_downloaded_app));
						popup.getMenu().getItem(1).setTitle(_activity.getString(R.string.detail_activity_view_detail_app));
					}else if(itemList.get(position).status == Constant.APP_STT_UPDATE)
					{
						popup.getMenu().getItem(0).setTitle(_activity.getString(R.string.detail_activity_update_app));
						popup.getMenu().getItem(1).setTitle(_activity.getString(R.string.detail_activity_remove_app));
					}else if(itemList.get(position).status == Constant.APP_STT_DOWNLOADING)
					{
						popup.getMenu().getItem(0).setTitle(_activity.getString(R.string.detail_activity_downloading_app));
					}
					else 
					{
						popup.getMenu().getItem(0).setTitle(_activity.getString(R.string.detail_activity_open_app_name));
						popup.getMenu().getItem(1).setTitle(_activity.getString(R.string.detail_activity_remove_app));
					}
					popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
						public boolean onMenuItemClick(MenuItem item) {
							if(item.getItemId() == R.id.add1)
							{
								// Install app
								Option1(position, holder);
							}else if(item.getItemId() == R.id.add2)
							{
								Option2(position, holder);
							}
								
							//							Toast.makeText(activity,
							//									"You Clicked : " + item.getTitle(),
							//									Toast.LENGTH_SHORT).show();
							return true;
						}
					});
					popup.setOnDismissListener(new OnDismissListener() {
						
						@Override
						public void onDismiss(PopupMenu arg0) {
							// TODO Auto-generated method stub
							((ImageView)v).setImageResource(R.drawable.ic_menu_light);
						}
					});
					popup.show();
				}
			});

			holder.btnViewAppStatus.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//v.setVisibility(View.INVISIBLE);


				}


			});
			return convertView;
		}
		private void Option1(final int pos, final ViewHolderProduct holder) {
			//			final TextView btn = holder.btnViewAppStatus;

			final ProductDTO item = itemList.get(pos);
//			holder.ivViewStatus.setVisibility(View.INVISIBLE);
			itemList.get(pos).isInvalidated = true;
			if(itemList.get(pos).status == Constant.APP_STT_NOTHING || 
					itemList.get(pos).status == Constant.APP_STT_UPDATE)
			{

				itemList.get(pos).status = Constant.APP_STT_DOWNLOADING;
				String url = SceneDetailItemActivity.URL_HEADER + item.filePath;
				final String packageName = item.packageName;
				DownloadTask downloader = new DownloadTask(context, null, new IOnDownload() {

					@Override
					public void OnFinished() {
						// TODO Auto-generated method stub

						String path = Environment.getExternalStorageDirectory()
								.getAbsoluteFile()
								+ "/Download/" + packageName + ".apk";
						File file = new File(path);
						
						itemList.get(pos).status = Constant.APP_STT_DOWNLOADED;
						itemList.get(pos).isInvalidated = true;
						adapter.notifyDataSetChanged();
						
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.putExtra("Position", pos);
						intent.setDataAndType(Uri.fromFile(file),
								"application/vnd.android.package-archive");
//						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivityForResult(intent,Constant.RECHECK_ALL_PAGE);

					}

					@Override
					public void OnError() {
						// TODO Auto-generated method stub
					}
				});
				DownloadQuere.Add(context, downloader, item.id, url, item.packageName);
				// Toast
				Toast.makeText(_activity, item.name +getString( R.string.toast_downloading), Toast.LENGTH_LONG).show();
			}
			if(itemList.get(pos).status == Constant.APP_STT_DOWNLOADED)
			{
//				itemList.get(pos).status = Constant.APP_STT_INSTALLING;
				// install app
				String path = Environment.getExternalStorageDirectory()
						.getAbsoluteFile()
						+ "/Download/" + item.packageName + ".apk";
				if(Installation.Install(context, path) == false)
				{
					Log.i("TAG", "Error when open app" + item.packageName);
				}

			}
			if(itemList.get(pos).status == Constant.APP_STT_INSTALLED)
			{
				
				// open app
				if(Installation.OpenApp(context, item.packageName) == false)
				{
					Log.i("TAG", "Error when open app" + item.packageName);
				}
			}
			
		}
	    private void Option2(final int pos, final ViewHolderProduct holder) {
			//			final TextView btn = holder.btnViewAppStatus;

			final ProductDTO item = itemList.get(pos);

			if(itemList.get(pos).status == Constant.APP_STT_NOTHING ||
					itemList.get(pos).status == Constant.APP_STT_DOWNLOADED )
			{
				Navigator.toDetailItem(_activity, itemList.get(pos).id);
			}
			if(itemList.get(pos).status == Constant.APP_STT_INSTALLED|| 
					itemList.get(pos).status == Constant.APP_STT_UPDATE)
			{
				Uri uri = Uri.fromParts("package", item.packageName, null);

				Intent it = new Intent(Intent.ACTION_DELETE, uri);

				startActivity(it);
			}
			itemList.get(pos).isInvalidated = true;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if(_lstItem != null && !isProductsLoading)
		{
			if(_lstItem.size()-2 > firstVisibleItem && _lstItem.size()-2 < firstVisibleItem+visibleItemCount)
			{
				Load();
			}
		}
	}
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		Navigator.toDetailItem(_activity, _lstItem.get(arg2));
	}
	public int getCatergory() {
		return catergory;
	}
	public void setCatergory(int catergory) {
		this.catergory = catergory;
		Reload();
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
		Reload();
	}



}
